using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace KlearTweet.Client.DataContainers
{
    public static class InfoController
    {
        private static InfoWindow _window;

        public static void Show(string message) // Always async
        {
            Infrastructure.ThreadPoolHelper.RunOnMainThread(() =>
            {
                if (_window == null)
                    _window = new InfoWindow();
                _window.Show();
                _window.Text.Text = message;
            });
        }


        public static void Show(Control parent, Control content)
        {
            // Compute the location of the popup so that it is next to the parent control (but not over it)
            var generalTransform = parent.TransformToVisual(Application.Current.RootVisual);
            var rect = new Rect(
                generalTransform.Transform(new Point()),
                generalTransform.Transform(new Point(
                    parent.RenderSize.Width,
                    parent.RenderSize.Height)));
            var x = rect.X - 200;
            var y = rect.Y + rect.Height;
            // TODO: Incomplete
            // TODO: Make sure that the content is fully visible in the Silverlight area

            var popup = new System.Windows.Controls.Primitives.Popup
            {
                Child = content,
                HorizontalOffset = x,
                VerticalOffset = y,
            };

            var timer = new System.Windows.Threading.DispatcherTimer();
            timer.Tick += (s, e) => CheckFocus(popup, parent, content);
            timer.Interval = new System.TimeSpan(0, 0, 0, 0, 100);
            popup.Opened += (s, e) => StartTimerWhenFocused(timer, parent, content);
            popup.Closed += (s, e) => timer.Stop();

            popup.IsOpen = true;
        }


        private static void StartTimerWhenFocused(System.Windows.Threading.DispatcherTimer timer, Control parent, Control content)
        {
            /*if (content.Focus())
            {
                var focusElt = System.Windows.Input.FocusManager.GetFocusedElement();
                if (focusElt == content) // Already has focus
                    StartTimer(timer);
                else
                    content.GotFocus += (s, e) => StartTimer(timer);
            }
            else if (parent.Focus())
            {
                var focusElt = System.Windows.Input.FocusManager.GetFocusedElement();
                if (focusElt == parent) // Already has focus
                    StartTimer(timer);
                else
                    parent.GotFocus += (s, e) => StartTimer(timer);
                //parent.GetGotFocus().Take(1).Subscribe(() => StartTimer(timer));
            }
            else*/ // Cannot use focus, so just start the timer now // TODO: Will probably result in the popup being closed immediatly
                StartTimer(timer);
        }

        private static void StartTimer(System.Windows.Threading.DispatcherTimer timer)
        {
            timer.Start();
        }


        private static void CheckFocus(System.Windows.Controls.Primitives.Popup popup, Control parent, Control content)
        {
            if(popup == null || !popup.IsOpen)
                return; // Ignore

            var focusElt = System.Windows.Input.FocusManager.GetFocusedElement() as DependencyObject;
            while (focusElt != null)
            {
                if (focusElt == content || focusElt == parent)
                    return; // Still has the focus
                focusElt = System.Windows.Media.VisualTreeHelper.GetParent(focusElt);
            }
            popup.IsOpen = false; // Lost focus
        }


        private static IObservable<Event<RoutedEventArgs>> GetGotFocus(this UIElement that)
        {
            return Observable.FromEvent<RoutedEventArgs>(that, "GotFocus");
        }
    }
}